package nancal.mp.config


import io.netty.buffer.Unpooled
import nbcp.base.comm.JsonResult
import nbcp.base.comm.const
import nbcp.base.extend.IsIn
import nbcp.base.extend.IsInItems
import nbcp.base.extend.ToJson
import org.springframework.http.HttpStatus
import org.springframework.http.server.reactive.ServerHttpResponse
import reactor.core.publisher.Mono

fun ServerHttpResponse.errorResponseJson(result: JsonResult): Mono<Void> {
    if (this.statusCode.value().IsInItems(200, 299)) {
        this.statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
    }

    this.headers.add("Content-Type", "application/json");

    var jsonBytes = result.ToJson().toByteArray(const.utf8);
    // 获取 DataBufferFactory 创建 DataBuffer
    val dataBufferFactory = this.bufferFactory()
    val dataBuffer = dataBufferFactory.allocateBuffer(jsonBytes.size)
    dataBuffer.write(jsonBytes)

    // 返回 writeWith，传入 Mono<DataBuffer>
    return this.writeWith(Mono.just(dataBuffer))
}